<?php

namespace addons\qingdong\controller;

use addons\qingdong\model\Contacts;
use addons\qingdong\model\Customer as CustomerModel;
use addons\qingdong\model\CustomerFile;
use addons\qingdong\model\CustomerOther;
use addons\qingdong\model\Business;
use addons\qingdong\model\Contract;
use addons\qingdong\model\FormField;
use addons\qingdong\model\StaffSignIn;
use addons\qingdong\model\Consume;
use addons\qingdong\model\Receivables;
use addons\qingdong\model\OperationLog;
use addons\qingdong\model\Form;
use addons\qingdong\model\Record;
use addons\qingdong\model\Record as RecordModel;
use addons\qingdong\model\Staff;
use addons\qingdong\model\StaffCollect;
use addons\qingdong\model\Message;
use think\Db;
use think\Exception;
use function EasyWeChat\Kernel\Support\get_client_ip;

/**
 * 操作文档：https://doc.fastadmin.net/qingdong
 * 软件介绍：https://www.fastadmin.net/store/qingdong.html
 * 售后微信：qingdong_crm
 * 客户接口
 */
class Customer extends StaffApi
{
    protected $noNeedLogin = [];
    protected $noNeedRight = [];


    //获取select客户列表
    public function getSelectList()
    {
        $name = input('name');
        $where = [];
        if ($name) {
            $where['name'] = ['like', "%{$name}%"];
        }

        $staff_id=$this->auth->id;
        $list = CustomerModel::where($where)->where(function ($query) use ($staff_id) {
            $query->where('ro_staff_id', 'like', "%,{$staff_id},%")
                ->whereOr('rw_staff_id', 'like', "%,{$staff_id},%")
                ->whereOr('owner_staff_id', 'in', Staff::getMyStaffIds());
        })->with(['ownerStaff'])->field('id,name,owner_staff_id,follow')->select();
        $this->success('请求成功', $list);
    }

    //获取客户列表
    public function getList()
    {
        $limit = input("limit/d", 10);
        $params = $this->request->post();

        $where= FormField::updateWhereField(FormField::CUSTOMER_TYPE,$params);

        $whereStaff = [];
        if (isset($params['name']) && $params['name']) {//客户名称
            if(is_numeric($params['name'])){
                $whereContact['mobile'] = ['like', "%".$params['name']."%"];
                $customer_id= Contacts::where($whereContact)->column('customer_id');
                $where['id'] = array('in',$customer_id);
            }else{
                $where['name|subname'] = ['like', "%{$params['name']}%"];
            }
        }
        if (isset($params['level']) && $params['level']) {//客户星级
            $where['level'] = $params['level'];
        }
        if (isset($params['source']) && $params['source']) {//客户来源
            $where['source'] = $params['source'];
        }
        if (isset($params['follow']) && $params['follow']) {//跟进状态
            $where['follow'] = $params['follow'];
        }
        if (isset($params['group_id']) && $params['group_id']) {//角色组
            $ids = Staff::getGroupStaffIds($params['group_id']);
            $where['id'] = ['in', $ids];
        }
        if (isset($params['createtime']) && $params['createtime']) {//
            $createtime = $params['createtime'];
            $createtime = explode(',', $createtime);
            $where['createtime'] = ['between', [strtotime($createtime[0]), strtotime($createtime[1]) + 86400 - 1]];
        }
        $order = 'id desc';
        if (isset($params['sort']) && $params['sort']) {
            switch ($params['sort']) {
                case 1://名称正序
                    $order = 'name asc';
                    break;
                case 2://名称倒序
                    $order = 'name desc';
                    break;
                case 3://创建时间正序
                    $order = 'createtime asc';
                    break;
                case 4://创建时间倒序
                    $order = 'createtime desc';
                    break;
                case 5://下次跟进时间正序
                    $order = 'next_time asc';
                    break;
                case 6://下次跟进时间倒序
                    $order = 'next_time desc';
                    break;
            }
        }

        if (isset($params['next_time']) && $params['next_time']) {//下次联系时间
            $next_time = $params['next_time'];
            $next_time = explode(',', $next_time);
            $where['next_time'] = ['between', [$next_time[0], $next_time[1]]];
        }
        if (isset($params['staff_id']) && $params['staff_id']) {//下级员工筛选
            $where['owner_staff_id'] = $params['staff_id'];
        } else {
            $staff_id = $this->auth->id;
            $type = $params['type'] ?? 0;
            if ($type == 1) {//我的客户
                $whereStaff['owner_staff_id'] = $this->auth->id;
            } elseif ($type == 2) {//下属负责的客户
                $whereStaff['owner_staff_id'] = ['in', Staff::getLowerStaffId()];
            } elseif ($type == 3) {//我参与的客户
                $whereStaff = function ($query) use ($staff_id) {
                    $query->where('ro_staff_id', 'like', "%,{$staff_id},%")
                        ->whereOr('rw_staff_id', 'like', "%,{$staff_id},%");
                };
            }else{
                $whereStaff = function ($query) use ($staff_id) {
                    $query->where(['ro_staff_id' => ['like', "%,{$staff_id},%"]])
                        ->whereOr('rw_staff_id', 'like', "%,{$staff_id},%")
                        ->whereOr(['owner_staff_id' => ['in', Staff::getMyStaffIds()]]);
                };
            }

        }
        $whereSeas = ['owner_staff_id' => ['neq', 0]];
        if (isset($params['is_seas']) && $params['is_seas'] == 1) {//公海
            //公海权限
            $whereSeas=[];
            $where['owner_staff_id'] = 0;
            //公海权限
            $rules=Staff::getStaffRule('seas');
            $whereStaff = function ($query) use ($rules) {
                foreach ($rules as $rule) {
                    $query->whereOr(['seas_id' => ['like', "%,{$rule},%"]]);
                }
            };
            $order = 'sea_time desc';
        }
        if(is_array($whereStaff)){
            //查询会冲突
            $whereSeas=[];
        }

        if (isset($params['contract_status']) && $params['contract_status'] !== "") {
            $where['contract_status'] = $params['contract_status'];
        }
        $list = CustomerModel::where($where)->where($whereStaff)->where($whereSeas)->with([
            'ownerStaff',
            'contacts'
        ])->field('id,name,next_time,owner_staff_id,level,follow')->order($order)->paginate($limit);
        $this->success('请求成功', $list);
    }


    //查重客户名称
    public function selectName()
    {
        $name = input('name');
        if (CustomerModel::where(['name' => $name])->find()) {
            $this->error('客户名称已存在');
        }
        $this->success('当前客户名称可使用');
    }


    //新增客户
    public function addCustomer()
    {
        $params = $this->request->post();
        if (empty($params['customer'])) {
            $this->error('客户信息不能为空');
        }

        // 表单验证
        if (($result = $this->qingdongValidate($params['customer'], get_class(), 'create')) !== true) {
            $this->error($result);
        }
        $result = FormField::checkFields(FormField::CUSTOMER_TYPE,$params['customer']);
        if ($result !== true) {
            $this->error($result);
        }
        if (CustomerModel::where(['name' => $params['customer']['name']])->find()) {
            $this->error('客户名称已存在');
        }

        if (isset($params['is_event']) && $params['is_event'] == 1) {//是否创建跟进任务
            if (empty($params['event'])) {
                $this->error('跟进任务信息不能为空');
            }
            // 表单验证
            if (($result = $this->qingdongValidate($params['event'], str_replace(ucwords($this->request->controller()), 'Event', get_class()), 'create_task')) !== true) {
                $this->error($result);
            }

        }

        Db::startTrans();
        try {
            //线索转化
            $leads_id = '';
            if(isset($params['leads_id'])){
                $leads_id=$params['leads_id'];
            }
            $customerId = CustomerModel::createCustomer($params['customer'],$leads_id,$params['record']);
            if(isset($params['customer']['mobile']) && $params['customer']['mobile']){
                $retC = array(
                    'customer_id'=>$customerId,
                    'is_major'=>1,
                    'name'=>$params['customer']['name'],
                    'mobile'=>$params['customer']['mobile'],
                    'next_time'=>date('Y-m-d H:i:s'),
                );
                Contacts::createContacts($retC);
            }

            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result) {
            $this->success('新增客户成功',array('id'=>$customerId));
        }
    }


    //编辑客户
    public function editCustomer()
    {
        $id = input('id');
        $params = $this->request->post();
        $row = CustomerModel::where(['id' => $id])->find();
        if (empty($row)) {
            $this->error('客户信息不存在');
        }
        // 表单验证
        if (($result = $this->qingdongValidate($params, get_class(), 'edit')) !== true) {
            $this->error($result);
        }
        $result = FormField::checkFields(FormField::CUSTOMER_TYPE,$params,$id);
        if ($result !== true) {
            $this->error($result);
        }
        Db::startTrans();
        try {
            $result = CustomerModel::updateCustomer($params);
            if(isset($params['mobile']) && $params['mobile']){
                Contacts::where(array('customer_id'=>$id,'is_major'=>1))->update(array('mobile'=>$params['mobile'],'updatetime'=>time()));
            }
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('修改客户成功');
    }


    //获取子公司
    public function getLowerCustomer()
    {
        $id = input('id');
        $customers = CustomerModel::where(['parent_id' => $id])->with([
            'ownerStaff',
            'contacts'
        ])->field('id,name,next_time,owner_staff_id,level,follow')->select();

        $this->success('请求成功', $customers);
    }


    //客户详情
    public function customerDetail()
    {
        $id = input('id');
        $customer = CustomerModel::where(['id' => $id])->with([
            'createStaff',
            'ownerStaff',
            'contacts'
        ])->find();
        if (empty($customer)) {
            $this->error('信息不存在');
        }
        $customer = $customer->toArray();
        $customer['is_collect'] = StaffCollect::isCollect(StaffCollect::CUSTOMER_TYPE, $customer['id']) ? 1 : 0;

        if ($customer['owner_staff_id'] == $this->auth->id ||
            in_array($customer['owner_staff_id'],Staff::getLowerStaffId()) ||
        in_array($this->auth->id, explode(',', $customer['rw_staff_id'])) ) {
            $customer['operation'] = 'update';//修改权限
        } else {
            $customer['operation'] = 'read';//只读权限
        }

        $customer = CustomerOther::getOther($customer);
        $form = Form::getDataValue('customer',$customer);
        foreach($form as $ks=>$vs){
            //备注显示
            if($vs['component'] == 'textarea' && ($vs['config']['label'] == '备注信息' || $vs['config']['label'] == '备注')){
                $customer[$vs['id']] = isset($customer[$vs['id']]) ? $customer[$vs['id']] :$customer['remarks'];
            }
        }
        //商机数量
        $customer['bussinessCount'] = Business::where(['customer_id'=>$id])->count();
        //联系人数量
        $customer['contactsCount'] = Contacts::where(['customer_id'=>$id])->count();
        //签到数量
        $customer['signCount'] = StaffSignIn::where(['customer_id'=>$id])->count();
        //合同数量
        $customer['contractCount'] = Contract::where(['customer_id'=>$id])->count();
        //费用数量
        $customer['consumeCount'] = Consume::where(['customer_id'=>$id])->count();
        //回款数量
        $customer['receivalbleCount'] = Receivables::where(['customer_id'=>$id])->count();
        //子公司
        $customer['companyCount'] = CustomerModel::where(['parent_id'=>$id])->count();
        //团队
        $ro_staff_id = [];
        if($customer['ro_staff_id']){
            $ro_staff_id = array_unique(array_filter(explode(',',$customer['ro_staff_id'])));
        }
        $rw_staff_id = [];
        if($customer['rw_staff_id']){
            $rw_staff_id = array_unique(array_filter(explode(',',$customer['rw_staff_id'])));
        }
        $customer['teamCount'] = count($ro_staff_id)+count($rw_staff_id);
        //附件
        $customer['fileCount'] = CustomerFile::where(['customer_id'=>$id])->count();
        //操作记录
        $customer['operateCount'] = OperationLog::where(['relation_id'=>$id,'relation_type'=>1,'operation_type' => 1])->count();
        //标记通知已读
        Message::setRead(Message::CUSTOMER_TYPE, $id, $this->auth->id);
        $this->success('请求成功', $customer);
    }


    //移入公海
    public function moveSeas()
    {
        $id = input('id');
        $row = CustomerModel::where(['id' => $id, 'owner_staff_id' => $this->auth->id])->find();
        if (empty($row)) {
            $this->error('您不是负责人暂无权限移除');
        }
        Db::startTrans();
        try {
            CustomerModel::moveSeas($id);

            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('放入成功');
    }


    //转移客户
    public function transfer()
    {
        $id = input('id');
        $staff_id = input('staff_id');
        if (empty($staff_id)) {
            $this->error('参数错误');
        }
        $staff = Staff::get($staff_id);
        if (empty($staff)) {
            $this->error('接收对象不存在');
        }
        $row = CustomerModel::where(['id' => $id])->find();
        if (empty($row)) {
            $this->error('客户不存在');
        }
        try {
            CustomerModel::transfer($id, $staff_id);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('转移客户成功');
    }


    //领取公海客户
    public function receive()
    {
        $customer_id = input('customer_id');
        $where = ['owner_staff_id' => 0];
        if ($customer_id) {
            $where['id'] = $customer_id;
        }
        $customers = CustomerModel::where($where)->count();
        if ($customers == 0) {
            $this->error('公海内暂无客户');
        }
        try {
            $id = CustomerModel::receive($customer_id);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('领取成功', ['id' => $id]);
    }


    //重点关注客户
    public function collect()
    {
        $customer_id = input('customer_id');
        try {
            StaffCollect::addCollect(StaffCollect::CUSTOMER_TYPE, $customer_id);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('重点关注成功');
    }


    //取消重点关注
    public function cancelCollect()
    {
        $customer_id = input('customer_id');
        try {
            StaffCollect::cancel(StaffCollect::CUSTOMER_TYPE, $customer_id);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('取消重点关注成功');
    }


    //重点关注客户列表
    public function collectList()
    {
        $limit = input("limit/d", 10);
        $ids = StaffCollect::where(['staff_id' => $this->auth->id, 'relation_type' => 1])->column('relation_id');
        $list = CustomerModel::where(['id' => ['in', $ids]])->with([
            'ownerStaff',
            'contacts'
        ])->field('id,name,next_time,owner_staff_id,level,follow')->order('id desc')->paginate($limit);

        $this->success('请求成功', $list);
    }


    //获取附件列表
    public function getFilesList()
    {
        $id = input('customer_id');

        $files = CustomerFile::where(['customer_id' => $id])->field('file_id')->with(['file'])->select();
        $this->success('请求成功', $files);
    }


    //周围客户
    public function nearby()
    {
        $lng = input('lng');
        $lat = input('lat');
        //我的客户
        $type = input('type',0);
        //距离
        $distance = input('distance', 5, 'intval');
        $name = input('name', '', 'trim');

        if (empty($lng) && empty($lat)) {
            $this->error('参数错误');
        }

        $range = 180 / pi() * $distance / 6372.797; //里面的 1 就代表搜索 1km 之内，单位km
        $lngR = $range / cos($lat * pi() / 180);
        $maxLat = $lat + $range; //最大纬度
        $minLat = $lat - $range; //最小纬度
        $maxLng = $lng + $lngR; //最大经度
        $minLng = $lng - $lngR; //最小经度
        $where = ['lng' => ['between', [$minLng, $maxLng]], 'lat' => ['between', [$minLat, $maxLat]]];
        //客户分类
        $whereStaff=[];
        $staff_id=$this->auth->id;
        if ($type == 1) {//我的客户
            $whereStaff['owner_staff_id'] = $this->auth->id;
        } elseif ($type == 2) {//下属负责的客户
            $whereStaff['owner_staff_id'] = ['in', Staff::getLowerStaffId()];
        } elseif ($type == 3) {//我参与的客户
            $whereStaff = function ($query) use ($staff_id) {
                $query->where('ro_staff_id', 'like', "%,{$staff_id},%")
                    ->whereOr('rw_staff_id', 'like', ",{$staff_id},");
            };
        }else{
            $whereStaff = function ($query) use ($staff_id) {
                $query->where('ro_staff_id', 'like', "%,{$staff_id},%")
                    ->whereOr('rw_staff_id', 'like', "%,{$staff_id},%")
                    ->whereOr('owner_staff_id', 'in', Staff::getMyStaffIds());
            };
        }
        if ($name) {
            $where['name'] = ['like', "%{$name}%"];
        }
        $customers = CustomerModel::where($where)->where($whereStaff)->field('id,owner_staff_id,name,location,next_time,lng,lat,address_detail,follow')->with('ownerStaff')->select();
        $data = [];
        //所属员工列表
        $myStaffIds = Staff::getMyStaffIds();
        foreach ($customers as $k => $v) {
            if ($v['owner_staff_id'] == 0) {
                $v['type'] = 0;//公海
            } elseif ($v['owner_staff_id'] == $this->auth->id) {
                $v['type'] = 1;//自己的
            } elseif (in_array($v['owner_staff_id'], $myStaffIds)) {
                $v['type'] = 2;//团队的
            } else {
                $v['type'] = 3;//其他人
            }
            $v['juli_num'] = getdistance($lng, $lat, $v['lng'], $v['lat']);
            $v['juli'] = float_number($v['juli_num']);
            $data[$v['juli']][] = $v;
        }
        ksort($data);


        $result = [];
        foreach ($data as $v) {

            $result = array_merge($result, array_values($v));
        }
        $this->success('请求成功', $result);
    }


    //获取搜索员工列表
    public function getSearchStaffList()
    {
        $name = input('name','');
        $where = [];
        if($name){
            $where['name'] = ['like',"%$name%"];
        }
        $ids = Staff::getMyStaffIds();

        $staff = Staff::where([
            'id' => ['in', $ids],
            'status' => 1
        ])->where($where)->field('id,name,img,post')->select();
        $this->success('请求成功', $staff);
    }

}
